﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Text;

/// <summary>
/// Responsive Table Class
/// </summary>
public class ResponsiveTable
{
    public enum Sort
    {
        Ascending = 0,
        Descending
    }
    public ResponsiveTable()
    {
        Data = new List<ResponsiveTableRow>();
        this.TableId = Guid.NewGuid().ToString();
        int max = 0;
        int.TryParse(ConfigurationManager.AppSettings["_CONFIG_MAX_DISPLAYED_ROWS"], out max);
        this.MaximumRowDisplay = max;
    }
    public ResponsiveTable(List<ResponsiveTableRow> data)
    {
        this.Data = data;
        this.TableId = Guid.NewGuid().ToString();
        int max = 0;
        int.TryParse(ConfigurationManager.AppSettings["_CONFIG_MAX_DISPLAYED_ROWS"], out max);
        this.MaximumRowDisplay = max;
    }
    public List<ResponsiveTableRow> Data { get; set; }
    public List<ResponsiveTableField> Fields { get; set; }
    public int MaximumRowDisplay { get; set; }
    public int Page { get; set; }
    public int TotalData { get; set; }
    public string TableId { get; set; }
    public string CustomHeader { get; set; }
    public string CustomButton { get; set; }
    public string AddAction { get; set; }
    public string EditAction { get; set; }
    public string DeleteAction { get; set; }
    public string SelectAction { get; set; }
    public string SortBy { get; set; }
    public Sort SortDirection { get; set; }
    public void AddField(ResponsiveTableField field)
    {
        Fields.Add(field);
    }
    public string RenderTable()
    {
        StringBuilder sb = new StringBuilder();
        int maxPriority = 1;

        // render toolbar
        sb.Append("<div class=\"tableButtons\" data-table-id=\"" + TableId + "\" ><div class=\"totalDataText\">" + (TotalData == 0 ? "No" : TotalData.ToString()) + " data found.</div>" + (!string.IsNullOrEmpty(CustomButton) ? CustomButton : "") + (!string.IsNullOrEmpty(AddAction) ? " <button class=\"button btnAddData medium primary\" onclick=\"" + AddAction + "\"><span class=\"icon icon-plus-2\"></span> Add New Item</button>" : "") + (!string.IsNullOrEmpty(DeleteAction) ? "<button class=\"button btnDeleteData medium danger\" onclick=\"" + DeleteAction + "\"><span class=\"icon icon-cancel-2\"></span> Delete Selected Item</button>" : "") + "</div>");

        if (this.Data.Count > 0)
        {
            bool hasActionColumn = !string.IsNullOrEmpty(this.EditAction) || !string.IsNullOrEmpty(this.SelectAction);
            bool hasDtlViewOnlyColumn = false;

            sb.Append("<table id=\"" + TableId + "\" class=\"responsiveTable table bordered hovered\" ><thead>");
            // render header
            if (!string.IsNullOrEmpty(CustomHeader))
            {
                sb.Append(CustomHeader);
            }
            else
            {
                sb.Append("<tr>");
                if (!string.IsNullOrEmpty(DeleteAction))
                {
                    sb.Append("<td class=\"tblHeader checks\" ><div class=\"input-control checkbox\"><label><input type=\"checkbox\" class=\"btnCheckAll\" onclick=\"_fw_table_checkall(this)\" /><span class=\"check\"></span></label></div></td>");
                }
                string _sort;
                foreach (ResponsiveTableField item in Fields)
                {
                    if (item.DetailViewOnly) hasDtlViewOnlyColumn = true;

                    _sort = (!string.IsNullOrEmpty(SortBy) && (SortBy == item.FieldName) ? ((SortDirection == null) || (SortDirection == Sort.Ascending) ? "ascending" : "descending") : "");
                    if ((int)item.Priority + 1 > maxPriority) maxPriority = (int)item.Priority + 1;

                    sb.Append("<th class=\"tblHeader " + (item.IsMainField ? "mainfield " : "") + (item.Sortable ? "sortable " : "") + " text-" + item.FieldAlign.ToString().ToLower() + " " + item.Priority.ToString().ToLower() + (item.Hidden || item.DetailViewOnly ? " hidden" : "") + "\" style=\"" + (!string.IsNullOrEmpty(item.Width) ? "width:" + item.Width : "") + "\" data-field-id=\"" + item.FieldName + "\"><a href=\"#\" onclick=\"" + (item.Sortable ? "_fw_table_sort(this,'" + item.FieldName + "','" + (_sort == "descending" ? "asc" : "desc") + "'); " : "") + "return false;\">" + item.FieldTitle + " <span class=\"sorticon " + _sort + (!string.IsNullOrEmpty(_sort) ? (_sort == "descending" ? " icon-arrow-down-4" : " icon-arrow-up-4") : "") + "\"></span></a></th>");
                }
                if (hasActionColumn) sb.Append("<th class=\"tblHeader actioncolumn text-center priority1\" >Actions</th></tr>");
            }
            sb.Append("</thead><tbody>");

            // render data
            ResponsiveTableItem _itm;
            StringBuilder _sbDetail = new StringBuilder();
            string _sbDetailGuid;
            foreach (ResponsiveTableRow row in Data)
            {
                sb.Append("<tr>");
                if (!string.IsNullOrEmpty(DeleteAction))
                {
                    sb.Append("<td class=\"tblData checks\" ><div class=\"input-control checkbox\"><label><input type=\"checkbox\" name=\"chkItem\" onclick=\"_fw_table_check(this)\" /><span class=\"check\"></span></label></div></td>");
                }
                _sbDetail = new StringBuilder("<div class=\"tblDetailView dtlpriority" + maxPriority + " hidden" + "\">"); // untuk detail view mobile 
                _sbDetailGuid = Guid.NewGuid().ToString();
                foreach (ResponsiveTableField field in Fields)
                {
                    _itm = row.Items.FirstOrDefault(i => i.Key == field.FieldName);
                    if (_itm != null)
                    {
                        if (!field.IsMainField)
                        {
                            _sbDetail.Append("<div class=\"dtl" + field.Priority.ToString().ToLower()+ (field.DetailViewOnly? " visible":"") + "\"><div class=\"detailview-label\">" + field.FieldTitle + "</div><div class=\"detailview-value\">" + _itm.Value + "</div></div>");
                        }
                        sb.Append("<td data-field-id=\"" + field.FieldName + "\" class=\"tblData " + (field.IsMainField ? "mainfield" : "") + " text-" + field.FieldAlign.ToString().ToLower() + " " + field.Priority.ToString().ToLower() + (field.Hidden || field.DetailViewOnly ? " hidden" : "") + "\">" + (field.IsMainField ? "<a href=\"#\" class=\"linkdetail button icon-arrow-down-5 bg-transparent priority" + maxPriority + (hasDtlViewOnlyColumn ? " visible" : "") + "\" onclick=\"_fw_table_showdetail(this); return false;\"></a>" : "") + " <span class=\"field-value\">" + _itm.Value + "</span>" + (field.IsMainField && (maxPriority > 1) ? "<!--[DTL:" + _sbDetailGuid + "]-->" : "") + "</td>");
                    }
                }
                _sbDetail.Append("</div>");
                sb.Replace("<!--[DTL:" + _sbDetailGuid + "]-->", _sbDetail.ToString());
                if (hasActionColumn)
                {
                    sb.Append("<td class=\"tblData actioncolumn text-center priority1 \">");
                    if (!string.IsNullOrEmpty(SelectAction))
                    {
                        sb.Append(" <a href=\"#\" class=\"linkselect button bg-transparent fg-darkCyan\" onclick=\"" + SelectAction + "; return false;\"><span class=\"icon-checkmark\"></span> <span class=\"actionlink-title\">Select</span></a> ");
                    }
                    if (!string.IsNullOrEmpty(EditAction))
                    {
                        sb.Append(" <a href=\"#\" class=\"linkedit button bg-transparent fg-darkCyan\" onclick=\"" + EditAction + "; return false;\"><span class=\"icon-pencil\"></span> <span class=\"actionlink-title\">Edit</span></a> ");
                    }
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
        }

        // render paging
        int TotalPage = (int)Math.Ceiling((double)TotalData / MaximumRowDisplay);
        if (TotalPage > 1)
        {
            StringBuilder sbPager = new StringBuilder("<div class=\"input-control select\" data-role=\"input-control\"><select name=\"selectPage\" onchange=\"_fw_tableGotoPage(this,$(this).val())\">");
            for (int a = 1; a <= TotalPage; a++)
            {
                sbPager.Append("<option value=\"" + a + "\" " + (Page == a ? " selected=\"selected\"" : "") + ">Page " + a + "</option>");
            }
            sbPager.Append("</select></div>");
            sb.Append("<div class=\"tablePaging\"  data-table-id=\"" + TableId + "\">" + (Page > 1 ? "<a href=\"#\" class=\"icon icon-first-2 button medium default\" onclick=\"_fw_tableGotoPage(this,1); return false;\"></a> <a href=\"#\" class=\"icon icon-arrow-left-4 button medium default\" onclick=\"_fw_tableGotoPage(this," + (Page - 1 < 1 ? 1 : Page - 1) + "); return false;\"></a> " : "") + sbPager.ToString() + (Page < TotalPage ? " <a href=\"#\" class=\"icon icon-arrow-right-4 button medium default\" onclick=\"_fw_tableGotoPage(this," + (Page + 1 > TotalPage ? TotalPage : Page + 1) + "); return false;\"></a> <a href=\"#\" class=\"icon icon-last-2 button medium default\" onclick=\"_fw_tableGotoPage(this," + TotalPage + "); return false;\"></a>" : "") + "</div>");
        }

        return sb.ToString();
    }
}

/// <summary>
/// Cells' class for Responsive Table
/// </summary>
public class ResponsiveTableItem
{
    public ResponsiveTableItem() { }
    public ResponsiveTableItem(string key, string value) { this.Key = key; this.Value = value; }
    public string Key { get; set; }
    public string Value { get; set; }
}

/// <summary>
/// Rows class for Responsive Table
/// </summary>
public class ResponsiveTableRow
{
    public ResponsiveTableRow() { }
    public ResponsiveTableRow(List<ResponsiveTableItem> rowItem) { Items = rowItem; }
    public List<ResponsiveTableItem> Items { get; set; }
    public void AddRow(List<ResponsiveTableItem> rowItem)
    {
        Items = rowItem;
    }
}

/// <summary>
/// Header Fields class for Responsive Table 
/// </summary>
public class ResponsiveTableField
{
    public enum FieldAlignment
    {
        Left = 0,
        Center,
        Right,
        Justify
    }
    public enum DisplayPriority
    {
        Priority1 = 0,
        Priority2,
        Priority3,
        Priority4
    }
    public ResponsiveTableField() { this.Hidden = false; FieldAlign = FieldAlignment.Left; IsMainField = false; Priority = DisplayPriority.Priority1; Sortable = false; }
    public string FieldName { get; set; }
    public string FieldTitle { get; set; }
    public string Width { get; set; }
    public bool IsMainField { get; set; }
    public FieldAlignment FieldAlign { get; set; }
    public Boolean Hidden { get; set; }
    public Boolean DetailViewOnly { get; set; }
    public DisplayPriority Priority { get; set; }
    public Boolean Sortable { get; set; }
}

